package org.scboy.dbms.service.imp;

import java.util.List;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.dao.RequestDesignDao;
import org.scboy.dbms.loads.LoadRequestDesign;
import org.scboy.dbms.service.RequestDesignService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hutool.crypto.digest.MD5;

@Service
public class RequestDesignServiceImpl implements RequestDesignService {

	@Autowired
	EntityFactory factory;

	@Autowired
	LoadRequestDesign cache;
	
	
	@Override
	public Page page(Model params) {
		RequestDesignDao dao=factory.getDao(RequestDesignDao.class);
		params.orderBy("code").addNrc("designContext");
		return dao.page(params);
	}

	@Override
	public boolean add(Model params) {
		RequestDesignDao dao=factory.getDao(RequestDesignDao.class);
		String id=MD5.create().digestHex(params.getString("code")+"_"+params.getString("appName"));
		if(dao.count(Model.create().add("id", id))>0) {
			return false;
		}
		params.add("id", id);
		int count = dao.insert(params);
		if(count>0) {
			cache.updateByKey(id);
			return true;
		}else {
			return true;
		}
	}

	@Override
	public boolean update(Model params) {
		RequestDesignDao dao=factory.getDao(RequestDesignDao.class);
		int count = dao.update(params);
		if(count>0) {
			cache.updateByKey(params.getString("id"));
			return true;
		}else {
			return true;
		}
	}

	@Override
	public Model get(String id) {
		RequestDesignDao dao=factory.getDao(RequestDesignDao.class);
		return dao.get(Model.create().add("id", id).addNrc("designContext"));
	}

	@Override
	public boolean delete(String id) {
		RequestDesignDao dao=factory.getDao(RequestDesignDao.class);
		int count= dao.delete(Model.create().add("id", id));
		if(count>0) {
			cache.removeCache(id);
			return true;
		}else {
			return true;
		}
	}

	@Override
	public List<Model> list(String appName) {
		RequestDesignDao dao=factory.getDao(RequestDesignDao.class);
		return dao.select(Model.create().add("appName", appName).orderBy("code"));
	}

	@Override
	public Model getContent(String id) {
		RequestDesignDao dao=factory.getDao(RequestDesignDao.class);
		return dao.get(Model.create().add("id", id));
	}

	@Override
	public boolean activity(String id) {
		RequestDesignDao dao=factory.getDao(RequestDesignDao.class);
		Model model= get(id);
		if(model==null) {
			return false;
		}
		Integer activity=model.getInt("activity");
		if(activity==null) {
			activity=0;
		}
		if(activity>0) {
			activity=0;
		}else {
			activity=1;
		}
		int count=dao.update(Model.create().add("activity", activity), Model.create().add("id", id));
		if(count>0) {
			cache.updateByKey(id);
			return true;
		}else {
			return false;
		}
	}
}
